package com.dk.controller;

import com.dk.shiro.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LoginController {
    @RequestMapping("tologin")
    public String tologin(){
        return "login";
    }

    @RequestMapping("login")
    public  String login(Model model,String userName, String password){
//
//        //什么是盐 （1234+字符串   md5次数
//        String salt =ShiroUtils.generateSalt(3);
//        System.out.println("盐 = " + salt);
//        //hash
//        String  md5 =ShiroUtils.encryptPassword("MD5","1234",salt,1);
//
//        System.out.println("密文 = "+md5);
        //使用shiro登录
        //1.获取subject对象(用户主体)
        Subject subject = SecurityUtils.getSubject();
        //2.封装用户登录数据，将用户名和密码封装成token
        UsernamePasswordToken token =new UsernamePasswordToken(userName,password);
        //3.执行登录
        //在公司中，如果我们手动抛出一些异常，并不一定代表真的出现错误，很有可能是业务不对，我们给调用方提示
        //比如
        try{
            subject.login(token);
            model.addAttribute("message","登录成功");
//            return "redirect:/index";
        }catch (UnknownAccountException e){
            System.out.println("账号错误");
            model.addAttribute("message","账号不存在");
            return "login";
        }catch (IncorrectCredentialsException e){
            System.out.println("密码错误");
            model.addAttribute("message","密码错误");
            return "login";
        }

        //登录成功跳转到首页
        return  "redirect:/index";
    }
}
